<?php
// 设置允许的来源，这里假设允许来自 http://1.13.198.191:8081 的请求
// header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
header("Access-Control-Allow-Origin: http://localhost:9528");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "./conn.php";
require_once "./usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 500, 'Ret' => "False", "Data" => "", "Msg" => "" . $conn->connect_error]));
}
// 获取前端传递的 JSON 数据
$data = json_decode(file_get_contents("php://input"), true);

$search = isset($data['search']) ? $data['search'] : '';
$page = isset($data['page']) ? intval($data['page']) : 1;
$pageSize = isset($data['pageSize']) ? intval($data['pageSize']) : 10;

$offset = ($page - 1) * $pageSize;

if ($search) {
    $sql = "SELECT * FROM configurations WHERE zhongkong_name = '$username' AND name LIKE '%$search%' ORDER BY modifyTime DESC LIMIT $offset, $pageSize";
    $countSql = "SELECT COUNT(*) as total FROM configurations WHERE zhongkong_name = '$username' AND name LIKE '%$search%'";
} else {
    $sql = "SELECT * FROM configurations WHERE zhongkong_name = '$username' ORDER BY modifyTime DESC LIMIT $offset, $pageSize";
    $countSql = "SELECT COUNT(*) as total FROM configurations WHERE zhongkong_name = '$username'";
}

$result = $conn->query($sql);
$data = [];
// if ($result->num_rows > 0) {
//     while ($row = $result->fetch_assoc()) {
//         $data[] = $row;
//     }
// }
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // 假设字段内容是 JSON 字符串，先解码为数组
        foreach ($row as $key => $value) {
            if (is_string($value) && is_json($value)) {
                $row[$key] = json_decode($value, true);
            }
        }
        $data[] = $row;
    }
}

// 辅助函数：判断字符串是否为合法 JSON
function is_json($string)
{
    json_decode($string);
    return json_last_error() === JSON_ERROR_NONE;
}
$countResult = $conn->query($countSql);
$countRow = $countResult->fetch_assoc();
$total = isset($countRow['total']) ? (int)$countRow['total'] : 0;

$total = isset($countRow['total']) ? (int)$countRow['total'] : 0;
// echo json_encode([
//     "Code" => 200,
//     "Data" => $data,
//     "total" => $total,
//     "Msg" => "查询成功",
//     "Ret" => "True"
// ]);
echo json_encode([
    "Code" => 200,
    "Data" => $data,
    "total" => $total,
    "Msg" => "查询成功",
    "Ret" => "True"
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$conn->close();
